<?php

class GroupsController extends AppController {
    public $helpers=array('Js'=>array('Jquery'),'Html', 'Form', 'calendar');
    public $uses = array ('PlaceCity', 'Group', 'Action', 'ActionPost', 'ActionPolls','ActionLaws', 'ActionEvents', 'GroupsNotificationsUser',  'GroupsNotification');    
            public function beforeFilter(){
        $group = $this->getCurrentUserGroup();
        $this->set('data2', $group);
}
    public $layout = 'group';

    /**
     * Nombre de personne maximum initial dans un groupe
     */
    const NB_PERS_MAX_INITIAL = 15;
    /**
     * Nombre de personne minimal pour qu'un groupe passe du status de "proposition" au status "active"
     */
    const NB_PERS_MIN_FOR_ACTIVE_STATUS = 5;
    
    /**
     * Définition des messages de notification pour un groupe
     */
    static $notificationsMessages = array(
        1 => 'Le groupe a changé de statut.', 
        
        
    );
    
    
    public function view($id){
        
        
        $data = $this->Group->getGroup('first', array('conditions' => array('Group.id' => $id)));
        
        $this->set('data', $data);
        $this->set('currentUser', $this->getCurrentUser());
    }
    
    public function join($id, $forced = false){
        
        
        $group = $this->Group->getGroup('first', array(
            'conditions' => array(
                'Group.id' => $id
            )
        ));
        $this->set('data', $group);
        
        // Si le groupe existe
        if (!empty($group)){
        
            $currentUser = $this->getCurrentUser();
            $currentUserId = $currentUser['User']['id'];
            // Si l'utilisateur a déja un groupe
            if (!empty($currentUser['UserGroup']['id'])){
                // Si il est déja dans ce groupe
                
                if ($currentUser['UserGroup']['groups_id'] == $id){
                    $this->redirect(array('controller' => 'Groups', 'action' => 'view', $id));
                }
                else if ($forced){
                    $this->delUserGroup($id, $currentUserId, 'leaveGroup');
                    $this->addUserGroup($id, $currentUserId);
                    $result = 'joinSuccess';
                }
                else{
                    $result = 'hasAlreadyAGroup';
                }
            }
            // Si on peut l'inscrire dans le groupe
            else{
               
                if ($this->addUserGroup($id, $currentUserId)){
                    
                    
                    $result = 'joinSuccess';
                }
                
                else{           
                    throw new Exception("Erreur lors de la sauvegarde");
                }
            }


            $this->set('group', $group);
            $this->set('result', $result);
            $this->set('currentUser', $currentUser);
        }
        else{            
            $this->Session->setFlash("Vous avez essayer d'accédé a un groupe qui n'existe pas ou plus.");
            $this->redirect(array('controller' => 'Groups', 'action' => 'index'));
            // Le groupe n'éxiste pas
        }
        
    }
    
    public function delUserGroup($groupId, $userId, $status = 'leaveGroup'){    
        
        $this->addNotificationUser(array(
            'GroupsNotificationsUser' => array(
                'users_id' => $userId,
                'type' => $status
            ),
            'GroupsNotification' => array(
                'groups_id' => $groupId,
                'created_on' => date('c')
            )
        ));
        
        return $this->Group->UserGroup->deleteAll(array(
            'UserGroup.users_id' => $userId
        ));
    }
    
    public function addUserGroup($groupId, $userId){
        
        $group = $this->Group->find('first', array(
            'conditions' => array(
                'Group.id' => $groupId,
            ),
            'fields' => array('Group.status', 'Group.nb_pers_max', 'Group.id')
        ));
        
        $nbPers = $this->Group->countUsers($groupId);
        
        if ($nbPers >= $group['Group']['nb_pers_max']){
            throw new Exception('Nb personne maximun atteint pour ce groupe');
        }
        
        
        $data = array(
                    'UserGroup' => array(
                        'users_id' => $userId,
                        'groups_id' => $groupId,                
                        'status' => 'ask'
                    )
                );
        
        
        
        $typeNotification = 'askJoin';
       
        if ($group['Group']['status'] == 'proposition' ){
            $data['UserGroup']['status'] = 'in';
            $typeNotification = 'changeStatusin';
            if ($nbPers + 1 == self::NB_PERS_MIN_FOR_ACTIVE_STATUS){
                $group['Group']['status'] = 'active';
                $this->Group->save($group);
            }
        }
        
         $this->addNotificationUser(array(
            'GroupsNotificationsUser' => array(
                'users_id' => $userId,
                'type' => $typeNotification
            ),
            'GroupsNotification' => array(
                'groups_id' => $groupId,
                'created_on' => date('c')
            )
        ));
        
        
        $q =  $this->Group->UserGroup->save($data);
        
        return $q;
    }
    
    public function create_group($idVille) {
        
        
        $city = $this->PlaceCity->find('first',array(
            'conditions' => array(
                'PlaceCity.places_id'=>$idVille
            )
        ));       
        if (!empty($this->request->data)){
            
            $data = $this->request->data;
            $this->Group->set($data['Group']);
            
             if ($this->Group->validates()){
                $data['Group']['cities_id'] = $idVille;
                $data['Group']['status'] = 'proposition';
                $data['Group']['nb_pers_max'] = self::NB_PERS_MAX_INITIAL;
                $data['Group']['created_on'] = date('c');
                $this->Group->save($data);
                
                $view = new View($this);
                $displayHelper = $view->loadHelper('Display');
                $this->Session->setFlash('Vous avez bien proposer un nouveau groupe pour la ville de '.$displayHelper->getLink($city['PlaceCity'], 'PlaceCity'));
                $this->redirect(array('controller' => 'PlaceCities', 'action' => 'view', $idVille));
             }
        }
        
        
        
    }
    
    public function settings(){
        $user = $this->getCurrentUser();
        $data = $this->getGroupCurrentUser();
        
        $this->set('data', $data);
        $this->set('currentUser', $user);
    }
    
    public function home(){
        $user = $this->getCurrentUser();
        $data = $this->getGroupCurrentUser();
        
// Find all //
        
        $actions = $this->Action->find('all', array(
            'fields' => array ('Action.*','ActionPoll.*','ActionLaw.*','ActionPost.*','ActionEvent.*'),
            'conditions' => array(
                'Action.groups_id' => $this->getCurrentUserGroupId()
            ),
            'order' => array('Action.created_on DESC'),
            'recursive' => 1,
            'limit' => 20
        ));     
        
        $groupsNotifications = $this->GroupsNotification->find('all', array(
            'conditions' => array(
                'GroupsNotification.groups_id' => $this->getCurrentUserGroupId()
            ),
            'order' => array('GroupsNotification.created_on DESC'),
            'recursive' => 1,
            'limit' => 20
        ));
        
 // Foreach //
        
        foreach ($actions as $key => $action){
            $actions[$key]['User'] = $this->loadUserById($action['Action']['users_id']);
        }
      
        foreach ($groupsNotifications as $key => $groupsNotification){
            $groupsNotifications[$key]['GroupsNotificationsUser']['User'] = $this->loadUserById($groupsNotification['GroupsNotificationsUser']['users_id']);
        } 
        
        if ($data['Group']['status'] == 'proposition'){
            $this->set('nbUsersMissingForActiveStatus', self::NB_PERS_MIN_FOR_ACTIVE_STATUS - count($data['UserGroup']) );
        }
        $this->set('actions', $actions);
        $this->set('groupsNotifications',$groupsNotifications);
        $this->set('data', $data);
        $this->set('currentUser', $user);
    }
    
    public function getGroupCurrentUser(){
        $user = $this->getCurrentUser();
        $data = $this->Group->getGroup('first', array(
            'conditions' => array(
                'Group.id' => $user['UserGroup']['groups_id']
            )
        ));
        
        return  $data;
    }
    
    public function leaveGroup(){
        $idGroup = $this->getCurrentUserGroupId();
        if ($idGroup){
            $this->delUserGroup($idGroup, $this->getCurrentUserId(), 'leaveGroup');
            $this->Session->setFlash('Vous avez quitter votre groupe');
        }
        $this->redirect(array('controller' => 'Places', 'action' => 'index'));
        
    }
    
    
    public function members(){
        $members = $this->Group->UserGroup->find('all', array(
            'conditions' => array(
                'UserGroup.groups_id' => $this->getCurrentUserGroupId()
            ), 
            'fields' => array('User.*', 'UserGroup.*'),
            'order' => array('UserGroup.status', 'User.name')
        ));
        
        $this->set('currentUser', $this->getCurrentUser());        
        $this->set('members', $members);      
        $this->set('data', $this->getCurrentUserGroup());
    }
    
    public function accepteUser($id, $userId){
        $this->changeUserStatus($id, $userId, 'in');
        
        $this->redirect(array('controller' => 'Groups', 'action' => 'members'));
        
        
    }
    public function refuseUser($id, $userId){        
        $this->delUserGroup($this->getCurrentUserGroupId(), $userId, 'refuseJoin');
        $this->redirect(array('controller' => 'Groups', 'action' => 'members'));
    }
    
    public function banUser($id, $userId){        
        $this->changeUserStatus($id, $userId, 'ban');
        $this->redirect(array('controller' => 'Groups', 'action' => 'members'));
    }
    
    public function ejectUser($id, $userId){        
        $this->delUserGroup($this->getCurrentUserGroupId(), $userId, 'ejectUser');
        $this->redirect(array('controller' => 'Groups', 'action' => 'members'));
    }
    
    public function changeUserStatus($id, $userId, $status){
        $data = array(
            'UserGroup' => array(
                'id' => $id,
                'status' => $status
            )
        );
        
        
        $this->addNotificationUser(array(
            'GroupsNotificationsUser' => array(
                'users_id' => $userId,
                'type' => 'changeStatus'.$status
            ),
            'GroupsNotification' => array(
                'groups_id' => $this->getCurrentUserGroupId(),
                'created_on' => date('c')
            )
        ));
        
        
        $this->Group->UserGroup->save($data);
        return 1;
        
    }
    
    
    
    
    
    public function addNotification($data){
        $this->GroupsNotification->id = null;
        return $this->GroupsNotification->save($data);
    }
    
    public function addNotificationUser($data){
        $info = $this->addNotification($data['GroupsNotification']);
        
        $data['GroupsNotificationsUser']['groups_notifications_id'] = $info['GroupsNotification']['id'];
        $this->GroupsNotificationsUser->save($data['GroupsNotificationsUser']);
    }
    
}

?>